<!--
 * @Description: 通用Tree组件
 * @Author: JiangMing
 * @Date: 2021-09-10 16:54:00
 * @LastEditors: JiangMing
 * @LastEditTime: 2021-09-13 10:36:00
-->
<template>
  <view class="tree-wrapper">
    <view v-for="(item,index) in data" :key="index" class="tree-item">
      <label class="tree-item__label" @click="checkChange(item, !item.checked)">
        <checkbox :checked="item.checked" class="tree-item__checkbox" />
        <view class="tree-item__content">
          <image v-if="item.icon" :src="item.icon" class="tree-item__icon" />
          <text class="tree-item__title">{{ item[nodeLabel] }}</text>
        </view>
      </label>
      <tree :data="item.children" :nodeKey="nodeKey" :nodeLabel="nodeLabel" class="tree-item__children" />
    </view>
  </view>
</template>

<script>
export default {
  name: 'Tree',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    nodeKey: {
      type: String,
      default: 'id',
    },
    nodeLabel: {
      type: String,
      default: 'label'
    },
  },
  methods: {
    checkChange(row, checked) {
      this.$set(row, 'checked', checked)
      this.$emit('check-change', row, checked);
      if (row.children) {
        row.children.forEach(t => {
          this.checkChange(t, checked);
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-wrapper {
  padding: 0 20rpx;
}
.tree-item {
  .tree-item__label {
    display: flex;
    align-items: center;
    height: 72rpx;
  }
  .tree-item__checkbox {
    margin-right: 20rpx;
  }
  .tree-item__content {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    line-height: 40rpx;
  }
  .tree-item__icon {
    width: 40rpx;
    height: 40rpx;
    vertical-align: middle;
    margin-right: 20rpx;
  }
  .tree-item__title {
    vertical-align: middle;
    color: #1D1F24;
  }
  .tree-item__children {
    margin-left: 40rpx;
  }
}
</style>